package org.example.server;/**
 * @Description: TODO
 * @Author: sats@jz
 * @Date: 2024/12/24 20:50
 **/

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import org.example.model.RpcRequest;
import org.example.model.RpcResponse;
import org.example.pojo.User;
import org.example.serializer.JacksonSerializer;
import org.example.serializer.JdkSerializer;
import org.example.serializer.Serializer;
import org.example.service.UserService;

import java.io.IOException;

/**
 * @description TODO
 * @author sats@jz
 * @date 2024年12月24日 20:50
 */
public class UserServiceProxy implements UserService {
    private final static Serializer serializer = new JacksonSerializer();
    @Override
    public User getUser(User user){
        RpcRequest rpcRequest = RpcRequest.builder()
                .serviceName(UserService.class.getName())
                .methodName("getUser")
                .parameterTypes(new Class[]{User.class})
                .args(new Object[]{user})
                .build();
        try {
            byte[] serialize = serializer.serialize(rpcRequest);
            byte[] result;
            try (HttpResponse httpResponse = HttpRequest.post("http://localhost:8080")
                    .body(serialize)
                    .execute()) {
                result = httpResponse.bodyBytes();
            }
            RpcResponse rpcResponse = serializer.deserialize(result, RpcResponse.class);
            return (User) rpcResponse.getData();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
